import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;


@WebServlet("/blog")
public class BlogServlet extends HttpServlet {
    //json数据格式的转换
    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //博客列表页中已经使用了过了/blog下的doGet请求，但是
        //博客详情页还想继续用，这里就需要用query string来区分了
        //若请求中带有query string，也就是含有blogId这个参数，就说明是博客详情页发起的请求
        //若没有，则说明是博客列表页发起的请求
        resp.setContentType("application/json; charset=utf8");
        BlogDao blogDao = new BlogDao();
        String blogId = req.getParameter("blogId");
        if(blogId == null) { //说明是博客列表页
            List<Blog> blogList = blogDao.selectAll();
            resp.getWriter().write(objectMapper.writeValueAsString(blogList));
        } else { //说明是博客详情页
            Blog blog = blogDao.selectOne(Integer.valueOf(blogId));
            resp.getWriter().write(objectMapper.writeValueAsString(blog));
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.检查用户登录状态
        HttpSession session = req.getSession(false);
        if(session == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录，不能发布博客!");
            return;
        }
        User user = (User) session.getAttribute("user");
        if(user == null) {
            resp.setStatus(403);
            resp.setContentType("text/html; charset=utf8");
            resp.getWriter().write("当前未登录，不能发布博客!");
            return;
        }
        //2.获取博客标题和正文
        req.setCharacterEncoding("utf8");
        String title = req.getParameter("title");
        String content = req.getParameter("content");
        //3.构造Blog对象，插入数据库中
        Blog blog = new Blog();
        //blogId是自增主键，不用设置
        blog.setTitle(title);
        blog.setContent(content);
        blog.setUserId(user.getUserId());
        BlogDao blogDao = new BlogDao();
        blogDao.insert(blog);
        //4.返回主页
        resp.sendRedirect("blog_list.html");
    }
}
